package netty.io.demo.BIO;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = new ServerSocket();
    // 绑定 address port
    serverSocket.bind(new InetSocketAddress(10001));
    System.out.println("server start ......");
    
    // 每个 accept 都会对应一个线程来处理
    new Thread(new ServerTask(serverSocket.accept())).start();
  }
  
  private static class ServerTask implements Runnable {
    
    // 这里是 拿到 client
    private Socket socket;
    
    public ServerTask(Socket socket) {
      this.socket = socket;
    }
    
    @Override
    public void run() {
      try {
        // 从这里 拿到 client socket 输入输出
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        
        // 拿到 客户端数据
        String c = in.readUTF();
        System.out.println(Thread.currentThread().getName() + ":Accept client message: " + c);
        
        // 给 client 写数据
        out.writeUTF("hello, " + c);
        out.flush();
      } catch (IOException e) {
        throw new RuntimeException(e);
      } finally {
        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
